﻿using System;
using System.Security.Cryptography;
using System.Web.Security;

namespace ClassLibrary
{
    public static class Defender
    {
        public static string CreateSalt(int size)
        {
            var rng = new RNGCryptoServiceProvider();
            var buff = new byte[size];
            rng.GetBytes(buff);
            return Convert.ToBase64String(buff);
        }

        public static string CreatePasswordHash(string pwd, string salt)
        {
            string saltAndPwd = String.Concat(pwd, salt);
            string hashedPwd =
                  FormsAuthentication.HashPasswordForStoringInConfigFile(
                                                       saltAndPwd, "SHA1");
            hashedPwd = String.Concat(hashedPwd, salt);
            return hashedPwd;
        }

        public static bool VerifyPassword(string dbPasswordHash, string password)
        {
            const int saltSize = 5;
            string salt = dbPasswordHash.Substring(dbPasswordHash.Length - saltSize);
            string passwordHash = CreatePasswordHash(password, salt);
            string pH2 = CreatePasswordHash(password, salt);

            return dbPasswordHash.Equals(passwordHash);
        }
    }
}